<?php

namespace common\models\logics;

use Yii;
use yii\helpers\Html;
use common\models\base\Config;
use common\models\AmhrBuild;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%shop_product}}".
 *
 * @property int $id
 * @property string $name 产品名称
 * @property string $art_no 货号
 * @property string $slogan 促销语
 * @property string $cover 货品缩略图
 * @property int $material 货物类型：0实物，1虚拟商品
 * @property string $type_id 分类ID
 * @property string $brand_id 品牌ID
 * @property string $template_id 快递模版ID
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at 删除时间
 */
class ShopProductLogic extends \common\models\shop\ShopProduct {

    public function getVideo() {
        return $this->hasOne(ShopGoodsVideo::className(), ['goods_id' => 'id']);
    }

    public function getCategoryArray() {
        $categoryArray = [];
        $categories = $this->categories;
        if ($categories) {
            foreach ($categories as $category) {
                $categoryArray[] = $category->category_id;
            }
        }
        return $categoryArray;
    }

    public function getImages() {
        return $this->hasMany(ShopAttachment::className(), ['goods_id' => 'id']);
    }

    public function getThumbUrl() {
        return $this->cover ? Yii::getAlias('@attachUrl') . $this->cover : $this->cover;
    }

    public function getTransparentCover() {
//        if (!empty($this->images)) {
//            foreach ($this->images as $image) {
//                return $image->image;
//            }
//        }
        return $this->cover;
    }

    public function getCoverUrl() {
        if ($this->cover && stripos($this->cover, 'http://') === false && stripos($this->cover, 'https://') === false) {
            return Yii::getAlias('@attachUrl') . '/' . ltrim($this->cover, '/');
        }
        return $this->cover;
    }

    public function getSkuName() {
        return $this->getPropertys()->select(['sku_name'])->column();
    }

    public function getStorage() {
        return $this->getStock()->sum('stock');
    }

    public function getSales() {
        return $this->getStock()->sum('total-stock');
    }

    public function getAlbum() {
        return $this->hasMany(ShopAttachment::className(), ['goods_id' => 'id']);
    }

    public function getPictures() {
        $album = $this->album;
        $pictures = [];
        if ($album) {
            foreach ($album as $picture) {
                $pictures[$picture->id] = $picture->image;
            }
        }
        return $pictures;
    }

    public function getShopCategories() {
        return $this->hasMany(ShopCategory::className(), ['id' => 'category_id'])
        ->viaTable('{{%shop_goods_categories}}', ['goods_id' => 'id']);
    }

    public function getGoodsStatistic() {
        return $this->hasOne(ShopGoodsStatistic::className(), ['goods_id' => 'id']);
    }

    public function getDefaultSales() {
        $default = round($this->price * pi());
        if ($this->statistic && $this->statistic->sales) {
            $default += $this->statistic->sales;
        }
        return $default;
    }

    public function getShareData($userid = 0) {
        $url = AmhrBuild::generateShareUrl([
            'from' => self::className(),
            'id' => $this->id,
            'user_id' => $userid,
        ]);
        return [
            'title' => $this->name,
            'desc' => $this->description ?: $this->introduction,
            'link' => $url,
            'img' => $this->coverUrl,
        ];
    }

    /**
     * 热销商品
     * @param type $num
     */
    public static function hotGoods($num = 1) {
        $query = static::find()->alias('t')->joinWith('statistic stat', false)
        ->andFilterWhere(['>', 'stat.widgets', 0])
        ->orderBy('rand()');
        if ($num > 1) {
            $query->limit($num)->all();
        }
        return $query->one();
    }

    public static function spread($userid = 0) {
        $id = Config::findValueByName('extend_goods_id');

        $goods = static::findOne($id);
        if ($goods) {
            $title = $goods->name;
            $cover = Config::findValueByName('extend_goods_cover') ?: $goods->coverUrl;
            $url = AmhrBuild::generateShareUrl([
                'from' => static::className(),
                'id' => $goods->id,
                'user_id' => $userid,
            ]);
            return compact('title', 'cover', 'url');
        }
        return null;
    }

    /**
     * 商品基本信息面板
     * Get member portlet panel.
     * @return string
     */
    public function getPortlet() {
        $title = $this->name;
        $subtitle = '';
        if ($this->propertysCount) {
            $subtitle = Html::tag('ol', '<li>' . implode("</li><li>", ['规格数量', $this->propertysCount]) . '</li>', ['class' => 'breadcrumb']);
        } else {
            $subtitle = Html::tag('p', '无规格商品', ['class' => 'font-blue-oleo']);
        }

        $img = $this->thumbUrl;
        if (!$img) {
            $img = Yii::$app->assetManager->getPublishedUrl('@common/themes') . '/images/undefined.png';
        }
        $thumb = Html::img($img, ['alt' => $title]);
        $details = Html::tag('h3', $title, ['class' => 'font-blue-dark']) . $subtitle;
        $content = Html::beginTag('div', ['class' => 'box-media box-media-lg']);
        $content .= Html::tag('div', $thumb, ['class' => 'bui-thumb']);
        $content .= Html::tag('div', $details, ['class' => 'bui-details']);
        return $content . Html::endTag('div');
    }

}
